
import 'dart:convert';
import 'dart:math';

import 'package:fep/bean/simple_account.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:fep/utils/print_tools.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pos_printer_platform/flutter_pos_printer_platform.dart';
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;



class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  PrintTools printTools = new PrintTools();
  late SimpleAccount _account;
  late String inputCardNo;
  late FocusNode _focusNode = FocusNode();
  late TextEditingController _editingController;

  @override
  void initState() {
    super.initState();
    _account = SimpleAccount();
    printTools.initPrint();
    _scan();
    _editingController = TextEditingController();
  }
  // https://blog.csdn.net/Saxxhw/article/details/125205631

  @override
  void dispose() {
    printTools.disposePrint();
    super.dispose();
  }

  Future getUserInfo (String cardNo) async {
    var url = Uri.parse('http://172.25.2.242:8086/jep/print/search');
    setState(() {
      _account = SimpleAccount();
    });
    // var url = Uri.parse('http://172.25.95.244:8086/jep/print/search');
    http.post(url, body: {'cardNo': cardNo}).then((response)  {
      if(response.statusCode == 200) {
        var decodedResponse = jsonDecode(utf8.decode(response.bodyBytes)) as Map;
        int _code = decodedResponse["code"];
        if(_code == 200) {
          setState(() {
            _account = SimpleAccount.fromJson(decodedResponse["data"]);
          });
        } else {
          String msg = "";
          if(_code == 403) {
            msg = "非用餐时间禁止刷卡";
          } else if(_code == 404) {
            msg = "人员不存在";
          } else {
            msg = "查询失败";
          }
          setState(() {
            inputCardNo = "";
          });
          FocusScope.of(context).requestFocus(_focusNode);
          _editingController.clear();
          _focusNode.nextFocus();
          _focusNode.previousFocus();
          // _editingController.text = "sdfs";
          showDiglog(msg);
        }
      } else {
        setState(() {
          inputCardNo = "";
        });
        showDiglog("Err: ${response.statusCode}");
      }
    });
    

  }



  // method to scan devices according PrinterType
  void _scan() {
    bool isNotPrint = false;
    printTools.getPrinterManagerContext().discovery(type: PrinterType.usb, isBle: false).listen((device) {
      if(device.name == "XP-80C") {
        isNotPrint = true;
      }
      setState(() {});
    }).onDone(() {
      if(isNotPrint) {
        showDiglog("打印设备安装正常.");
      } else {
        showDiglog("请检查打印设备是否安装正常.");
      }
    });
  }


  excuPrint() {

    if(null != _account && _account.cardNo.isNotEmpty) {
      var url = Uri.parse('http://172.25.2.242:8086/jep/print/saveLog');
      // var url = Uri.parse('http://172.25.95.244:8086/jep/print/saveLog');
      http.post(url, body: {'cardNo': _account.cardNo}).then((response)  {

        if(response.statusCode == 200) {
          var decodedResponse = jsonDecode(utf8.decode(response.bodyBytes)) as Map;
          int _code = decodedResponse["code"];
          if(_code == 200) {
            showDiglog("正在出票中...");
            _account.time = decodedResponse["data"];
            printTools.usbPrintTicket(_account);
          } else {
            setState(() {
              _account = SimpleAccount();
            });
            if(_code == 202) {
              showDiglog("请勿重复取票.");
            } else if(_code == 403) {
              showDiglog("非用餐时间禁止刷卡");
            } else if(_code == 404) {
              showDiglog("人员不存在");
            } else {
              showDiglog("查询失败");
            }
          }

        } else {
          showDiglog("Err: ${response.statusCode}");
        }
        clearPanel();
      });

    } else {
      printTools.usbPrintTicket(_account);
    }

  }

  void clearPanel() {
    setState(() {
      inputCardNo = "";
      _account = SimpleAccount();
    });
    FocusScope.of(context).requestFocus(_focusNode);
    _editingController.clear();
    _focusNode.nextFocus();
    _focusNode.previousFocus();
  }

  void showDiglog(String title) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('提示'),
            content: Text(title),
            actions: <Widget>[
              TextButton(child: const Text('确认'),onPressed: (){
                Navigator.of(context).pop(false);
              },),
            ],
          );
        });
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(),
      body: Column(
        children: [
          // 头部
          Container(
            child: Column(
              children: [
                Container(

                  padding: EdgeInsets.fromLTRB(10, 60, 10, 10),
                  child: Text("小票打印", style: TextStyle(fontSize: 34, fontWeight: FontWeight.bold,),),
                ),
                Container(
                  width: 900,
                  color: Colors.white70,
                  child: Row(
                    children: [
                      Container(
                        width: 620,
                        color: Colors.white70,
                        child: CupertinoTextField(
                          focusNode: _focusNode,
                          controller: _editingController,
                          placeholder: "请输入卡号",
                          autofocus: true,
                          showCursor: true,
                          minLines: 1,
                          maxLines: 1,
                          maxLength: 10,
                          padding: EdgeInsets.all(8),
                          onTap: () {},
                          onChanged: (String value) {
                            setState(() {
                              this.inputCardNo = value;
                            });
                            print('onChanged:'+value);
                          },
                          onSubmitted: (String value) {
                            // FocusScope.of(context).requestFocus(_focusNode);
                            setState(() {
                              this.inputCardNo = value;
                            });
                            // _editingController.clear();
                            getUserInfo(value);
                            print('onSubmitted:'+value);
                          },


                        ),
                      ),

                      Container(
                        width: 250,
                        margin: EdgeInsets.fromLTRB(30, 0, 0, 0),
                        child: CupertinoButton(
                          padding: EdgeInsets.fromLTRB(70, 8, 70, 8),
                          borderRadius: BorderRadius.all(Radius.circular(3.0)),
                          pressedOpacity: 0.4,
                          color: Colors.orangeAccent,
                          child: Text("查询"),
                          onPressed: () {
                            getUserInfo(inputCardNo);
                          },
                        ),
                      ),

                    ],
                  ),
                ),

              ],
            )
          ),

          // 中间内容
          Container(
            width: 900,
            height: 428,
            // color: Colors.black12,
            margin: EdgeInsets.fromLTRB(0, 30, 0, 0),
            padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
            child: Row(
              children: [
                // 个人档案信息
                Container(
                  width: 449,
                  height: 430,
                  margin: EdgeInsets.fromLTRB(1, 1, 0, 1),
                  color: Colors.white,
                  child: getUserCard(),
                ),



                // 票据信息
                Container(
                  width: 448,
                  height: 428,
                  margin: EdgeInsets.fromLTRB(1, 1, 1, 1),
                  color: Colors.white,
                  child: getTicktCard(),
                ),


              ],
            ),
          ),

          // 底部
          Container(
            height: 90,
            alignment: Alignment.center,
            margin: EdgeInsets.fromLTRB(0, 30, 0, 0),
            // padding: EdgeInsets.all(20),
            child: Container(
              width: 180,
              child: CupertinoButton(
                color: Colors.blue,
                padding: EdgeInsets.fromLTRB(55, 0, 55, 0),
                alignment: Alignment.center,
                pressedOpacity: 0.4,
                borderRadius: BorderRadius.all(Radius.circular(3.0)),
                onPressed: () {
                  excuPrint();
                },
                child: Container(
                  child: Row(
                    children: [
                      Container(
                        width: 30,
                        child: Icon(Icons.print, color: Colors.white),
                      ),
                      Container(
                        width: 40,
                        child: Text("打印", style: TextStyle(color: Colors.white),),
                      ),
                    ],
                  ),
                ),
              ),
            ),

          ),
        ],
      ),
    );
  }




  Widget getCard (Widget child) {
    return DecoratedBox(
      decoration: BoxDecoration(
          border: Border.all(  // 边框，会绘制在背景颜色背景图片上面
            color: Colors.black12,
            width: 2.0,
          ),
          borderRadius: BorderRadius.all(Radius.circular(2.0)),  // 边框圆角
          shape: BoxShape.rectangle  // 形状:圆形、矩形
      ),
      // 个人信息
      child: child,
    );
  }

  Widget getUserCard() {
    Widget _c = Container(
      child: Column(
        children: getUserInfoWidget(),
      )
    );
    return getCard(_c);
  }

  List<Widget> getUserInfoWidget () {
    List<Widget> _list = [];
    _list.add(Container(
      alignment: Alignment.center,
      padding: EdgeInsets.fromLTRB(0, 15, 0, 5),
      child: Text("个人信息", style: TextStyle(fontSize: 24, fontWeight: FontWeight.w400), ),
    ));

    _list.add(Row(
      children: [
        Container(
          width: 200,
          height: 250,
          padding: EdgeInsets.fromLTRB(30, 0, 0, 0),
          alignment: Alignment.topLeft,
          child: Column(
            children: [
              getUserProerties("学号", _account.accountId),
              getUserProerties("姓名", _account.userName),
              getUserProerties("性别", _account.gender),
              getUserProerties("年级", _account.gradelevel),
              getUserProerties("班级", _account.deptid),
            ],
          ),
        ),
        Container(
          width: 170,
          height: 220,
          child: getPeoplePic(),
        ),
      ],
    ));
    return _list;
  }

  getPeoplePic () {
    if(null != _account && _account.img.isNotEmpty ) {
      return Image.network(_account.img, height: 220, width: 170,);
    } else {
      return Image.asset('assets/people.jpg');// new AssetImage('assets/people.jpg')
    }
  }

  Widget getTicktCard() {
    Widget _c = Container(
        child: Column(
          children: getTicktInfoWidget(),
        )
    );
    return getCard(_c);
  }
  List<Widget> getTicktInfoWidget () {
    List<Widget> _list = [];
    _list.add(Container(
      alignment: Alignment.center,
      padding: EdgeInsets.fromLTRB(0, 15, 0, 5),
      child: Text(_account.mealType != null ? _account.mealType : "票据信息", style: TextStyle(fontSize: 24, fontWeight: FontWeight.w400), ),
    ));
    _list.add(Container(
      width: 430,
      height: 250,
      padding: EdgeInsets.fromLTRB(30, 0, 0, 0),
      alignment: Alignment.topLeft,
      child: Column(
        children: [
          getUserProerties("餐厅", _account.position == null ? " - " : _account.position),
          getUserProerties("学号", _account.accountId),
          getUserProerties("姓名", _account.userName),
          getUserProerties("费用", _account.fee),
          // getUserProerties("时间", _account.time),
        ],
      ),
    ));


    return _list;
  }

  Widget getUserProerties(String title, String content) {
    return Container(
      alignment: Alignment.topLeft,
      padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
      child: Text(title + ":" + content, style: TextStyle(fontSize: 20, fontWeight: FontWeight.w200),),
    );
  }


}
